package com.ys.web.interceptor;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ys.WebConstants;
import com.ys.extend.utils.ResourceUtil;
import com.ys.web.entity.User;
import com.ys.web.pojo.SystemPermissonInfo;
import com.ys.web.security.SystemPermissionUtils;
import com.ys.web.service.SystemService;
import com.ys.web.service.UserService;

public class AuthInterceptor implements HandlerInterceptor {
	
	@Autowired
	SystemService systemService;
	
	@Autowired
	UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String requestPath = ResourceUtil.getRequestPath(request);
		HttpSession session = request.getSession();
		String username = "";
		session.setAttribute("path", requestPath);
		//System.out.println(requestPath);
		for(String permissonPath:WebConstants.PUBLIC_PAGE){
			if(permissonPath.equals(requestPath)){
				return true;
			}
		}
		
		if(session.getAttribute("username")==null||"".equals(session.getAttribute("username"))){
			response.sendRedirect("index.do");
			return false;
			
		}
		username = (String)session.getAttribute("username");
		
		SystemPermissonInfo systemPermissonInfo = SystemPermissionUtils.getUserPermission(username);
		
		//重新加载系统信息
		if(systemPermissonInfo==null){
			User user=userService.getUserByUsername(username);
			if(user==null){
				response.sendRedirect("index.do");
			}
			systemService.addSystemUserInfo(session, user);
		}
		
		for(String permissonPath:WebConstants.COMMON_PERMISSON){
			if(permissonPath.equals(requestPath)){
				return true;
			}
		}
		
		for(String permissonPath:WebConstants.SEM_USER_PERMISSON){
			if(permissonPath.equals(requestPath)){
				
				return true;
			}
		}
		
		for(String permissonPath:WebConstants.SUPER_USER_PERMISSION){
			//System.out.println(permissonPath);
			if(permissonPath.equals(requestPath)){
				
				return true;
			}
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
